package com.right.util.push;

import com.gexin.rp.sdk.base.IIGtPush;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsDateJsonValueProcessor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 个推工具
 *
 * @author mh 2018-08-27 上午10:24
 */

public class PushUtil {
    private static final String APPID = "Aj18piuYQs69O6HHzeHyu6";
    private static final String APPKEY = "vZrajbrFFB9Ytm1GBdrFj7";
    private static final String MASTERSECRET = "JXpAxT5SvE9bPypCH093I1";
    private static final String API = "http://sdk.open.api.igexin.com/apiex.htm";    //OpenService接口地址

    /**
     * 返回值
     */
    private static final int PUSH_SUCCESS = 1;
    private static final int PUSH_FAIL = 0;
    /**
     * 收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动
     */
    @SuppressWarnings("unused")
    private static final int TRANSMISSION_TYPE_IMMEDIATELY = 1;
    private static final int TRANSMISSION_TYPE_WAIT = 2;

    private PushUtil() {
    }

    /**
     * 推送给一个人
     *
     * deviceId 手机的deviceId
     * deviceType 1.安卓，2.IOS
     * text 推送的内容，如:退出登录
     * title 标题，如:优兴
     * unreadNum 未读消息总数
     * pushType 推送类型
     */
    public static int pushToSingle(String deviceId,Integer deviceType,String text,String title,Integer unreadNum,Integer pushType) {
        Device device = new Device();
        device.setDeviceId(deviceId);
        device.setDeviceType(deviceType);
        PushModel model = new PushModel();
        model.setText(text);
        model.setTitle(title);
        model.setUnReadNum(unreadNum);
        model.setPushType(pushType);
        List<String> deviceIds = new ArrayList<>();
        deviceIds.add(deviceId);
        if (device.getDeviceType() == Device.DEVICE_TYPE_ANDROID) {
            return pushToListForAndroid(APPID, APPKEY, MASTERSECRET, deviceIds, model);
        } else {
            return pushToListForIos(APPID, APPKEY, MASTERSECRET, deviceIds, model);
        }
    }

    /**
     * 推送给安卓用户
     *
     * @param deviceIds 设备信息
     * @param model     推送消息
     * @return int
     */
    private static int pushToListForAndroid(String appId, String appKey, String masterSecret, List<String> deviceIds,
                                            PushModel model) {
        // 显示每个用户的用户状态，false:不显示，true：显示
        System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
        // 推送主类
        IIGtPush push = new IGtPush(API, appKey, masterSecret);
        try {
            push.connect();
            TransmissionTemplate template = new TransmissionTemplate();
            ListMessage message = new ListMessage();
            // 通知模版
            template.setAppId(appId); // 应用APPID
            template.setAppkey(appKey); // 应用APPKEY
            template.setTransmissionType(TRANSMISSION_TYPE_WAIT);// 收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动
            template.setTransmissionContent(getJsonArrStrFromList(model)); // 透传内容（点击通知后SDK将透传内容传给你的客户端，需要客户端做相应开发）
            message.setData(template);
            message.setOffline(true);
            message.setOfflineExpireTime(24 * 3600 * 1000);
            // 接收者
            List<Target> targets = new ArrayList<>();
            Target target;
            for (String deviceId : deviceIds) {
                target = new Target();
                target.setAppId(appId);
                target.setClientId(deviceId);
                targets.add(target);
            }
            // 推送前通过该接口申请“ContentID”
            String contentId = push.getContentId(message);
            IPushResult ret = push.pushMessageToList(contentId, targets);
            System.out.println(ret.getResponse().toString());
            return PUSH_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return PUSH_FAIL;
        }
    }

    /**
     * 推送给IOS用户
     *
     * @param deviceIds 设备信息
     * @param model     推送消息
     * @return int
     */
    private static int pushToListForIos(String appId, String appKey, String masterSecret, List<String> deviceIds,
                                        PushModel model) {
        //显示每个用户的用户状态，false:不显示，true：显示
        System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
        // 推送主类
        IIGtPush push = new IGtPush(API, appKey, masterSecret);
        try {
            push.connect();
            ListMessage message = new ListMessage();
            TransmissionTemplate template = new TransmissionTemplate();
            template.setAppId(appId);                            //应用APPID
            template.setAppkey(appKey);                            //应用APPKEY
            template.setTransmissionType(TRANSMISSION_TYPE_WAIT);// 收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动

            template.setTransmissionContent(getJsonArrStrFromList(model));    // 透传内容（点击通知后SDK将透传内容传给你的客户端，需要客户端做相应开发）
            APNPayload payload = new APNPayload();
            payload.setAutoBadge("+1");
            payload.setContentAvailable(1);
            payload.setSound("default");
            payload.setCategory("$由客户端定义");
            //简单模式APNPayload.SimpleMsg
            //payload.setAlertMsg(new APNPayload.SimpleAlertMsg("hello"));
            //字典模式使用APNPayload.DictionaryAlertMsg
            payload.setAlertMsg(getDictionaryAlertMsg(model.getTitle(), model.getText()));
//            payload.addMultiMedia(new MultiMedia().setResType(MultiMedia.MediaType.video)
//                    .setResUrl("http://ol5mrj259.bkt.clouddn.com/test2.mp4")
//                    .setOnlyWifi(true));
            template.setAPNInfo(payload);

            message.setData(template);
            message.setOffline(true);
            message.setOfflineExpireTime(24 * 3600 * 1000);
            // 接收者
            List<Target> targets = new ArrayList<>();
            Target target;
            for (String deviceId : deviceIds) {
                target = new Target();
                target.setAppId(appId);
                target.setClientId(deviceId);
                targets.add(target);
            }
            //推送前通过该接口申请“ContentID”
            String contentId = push.getContentId(message);
            IPushResult ret = push.pushMessageToList(contentId, targets);
            System.out.println(ret.getResponse().toString());
            return PUSH_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return PUSH_FAIL;
        }
    }

    private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String title, String body) {
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setBody(body);
        alertMsg.setActionLocKey("ActionLockey");
        alertMsg.setLocKey("LocKey");
        alertMsg.addLocArg("loc-args");
        alertMsg.setLaunchImage("launch-image"); // iOS8.2以上版本支持
        alertMsg.setTitle(title);
        alertMsg.setTitleLocKey("TitleLocKey");
        alertMsg.addTitleLocArg("TitleLocArg");
        return alertMsg;
    }

    /**
     * 序列化操作，无论是单个的对象，还是list，抑或是list中的属性仍包含list，都可以直接序列化成String类型
     *
     * @param obj 需要被序列化的对象
     * @return 序列化之后的字符串
     */
    private static String getJsonArrStrFromList(Object obj) {
        //返回結果
        String jsonStr;
        //判空
        if (obj == null) {
            return "{}";
        }
        //Json配置
        JsonConfig jsonCfg = new JsonConfig();

        //注册日期处理器
        jsonCfg.registerJsonValueProcessor(java.util.Date.class,
                new JsDateJsonValueProcessor());

        //判断是否是list
        if (obj instanceof Collection || obj instanceof Object[]) {
            jsonStr = JSONArray.fromObject(obj, jsonCfg).toString();
        } else {
            jsonStr = JSONObject.fromObject(obj, jsonCfg).toString();
        }
        return jsonStr;
    }
}

